package com.example.bankseckill.exception;



import com.example.bankseckill.pojo.vo.RespBean;
import com.example.bankseckill.pojo.vo.RespBeanEnum;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {
    //捕捉异常
    @ExceptionHandler(Exception.class)
    public RespBean ExceptionHandler(Exception e){
        if(e instanceof GlobalException){
            GlobalException exception = (GlobalException) e;
            return RespBean.error(exception.getRespBeanEnum());
        }else if(e instanceof BindException){
            BindException ex = (BindException) e;
            RespBean error = RespBean.error(RespBeanEnum.BIND_ERROR);
            error.setMessage("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return error;
        }else if(e instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException ex = (MethodArgumentNotValidException) e;
            RespBean error = RespBean.error(RespBeanEnum.BIND_ERROR);
            error.setMessage("参数校验异常"+ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
            return error;
        }else if(e instanceof ClassCastException){
            ClassCastException ex = (ClassCastException) e;
            RespBean error = RespBean.error(RespBeanEnum.BIND_ERROR);
            error.setMessage("参数校验异常"+ex.getMessage());
            return error;
        }
        System.out.println(e);
        System.out.println(e.getMessage());
        System.out.println(e.getCause());
        return RespBean.error(RespBeanEnum.ERRPR);
    }
}
